package org.example.managere.controller;

import org.example.managere.dto.CompetingAircraftDTO;
import org.example.managere.service.CompetingAircraftService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 竞争机型控制器
 */
@RestController
@RequestMapping("/api/competing-aircraft")
public class CompetingAircraftController {

    @Autowired
    private CompetingAircraftService competingAircraftService;

    /**
     * 分页查询竞争机型列表
     */
    @GetMapping
    public ResponseEntity<Page<CompetingAircraftDTO>> findAll(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String sort,
            @RequestParam(required = false) String keyword) {
        
        // 构建分页参数
        Pageable pageable;
        if (sort != null && !sort.isEmpty()) {
            // 排序格式：字段,方向 例如：productName,asc
            String[] sortParams = sort.split(",");
            String sortField = sortParams[0];
            Sort.Direction direction = (sortParams.length > 1 && sortParams[1].equalsIgnoreCase("desc")) 
                    ? Sort.Direction.DESC : Sort.Direction.ASC;
            pageable = PageRequest.of(page, size, Sort.by(direction, sortField));
        } else {
            pageable = PageRequest.of(page, size);
        }
        
        // 执行查询
        Page<CompetingAircraftDTO> result = competingAircraftService.findAll(pageable, keyword);
        return ResponseEntity.ok(result);
    }

    /**
     * 根据ID查询竞争机型
     */
    @GetMapping("/{id}")
    public ResponseEntity<CompetingAircraftDTO> findById(@PathVariable Integer id) {
        return competingAircraftService.findById(id)
                .map(ResponseEntity::ok)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "找不到ID为 " + id + " 的竞争机型记录"));
    }
    
    /**
     * 获取指定产品的可靠性指标
     * 使用不同的URL路径前缀，避免与/{id}路径冲突
     */
    @GetMapping("/metrics/reliability")
    public ResponseEntity<Map<String, Object>> getReliabilityMetrics(@RequestParam("productName") String productName) {
        try {
            // 调用服务层方法获取空停率
            Double airShutdownRate = competingAircraftService.calculateAirShutdownRate(productName);
            
            // 调用服务层方法获取故障率
            Double faultRate = competingAircraftService.calculateFaultRate(productName);
            
            // 调用服务层方法获取发动机拆换率
            Double engineReplacementRate = competingAircraftService.calculateEngineReplacementRate(productName);
            
            // 调用服务层方法获取平均故障间隔时间(MTBF)
            Double mtbf = competingAircraftService.calculateMTBF(productName);
            
            // 调用服务层方法获取可靠性
            Double reliability = competingAircraftService.calculateReliability(productName);
            
            // 调用服务层方法获取维修频率
            Double maintenanceFrequency = competingAircraftService.calculateMaintenanceFrequency(productName);
            
            // 调用服务层方法获取使用困难报告频率
            Double difficultyReportRate = competingAircraftService.calculateDifficultyReportRate(productName);
            
            // 构建响应数据
            Map<String, Object> metrics = new HashMap<>();
            metrics.put("productName", productName);
            metrics.put("airShutdownRate", airShutdownRate);
            metrics.put("faultRate", faultRate);
            metrics.put("engineReplacementRate", engineReplacementRate);
            metrics.put("mtbf", mtbf);
            metrics.put("reliability", reliability);
            metrics.put("maintenanceFrequency", maintenanceFrequency);
            metrics.put("difficultyReportRate", difficultyReportRate);
            
            return ResponseEntity.ok(metrics);
        } catch (Exception e) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "计算可靠性指标失败: " + e.getMessage());
        }
    }

    /**
     * 创建竞争机型
     */
    @PostMapping
    public ResponseEntity<CompetingAircraftDTO> create(@Valid @RequestBody CompetingAircraftDTO dto) {
        // 确保新建时没有ID
        dto.setId(null);
        CompetingAircraftDTO saved = competingAircraftService.save(dto);
        return ResponseEntity.status(HttpStatus.CREATED).body(saved);
    }

    /**
     * 更新竞争机型
     */
    @PutMapping("/{id}")
    public ResponseEntity<CompetingAircraftDTO> update(
            @PathVariable Integer id,
            @Valid @RequestBody CompetingAircraftDTO dto) {
        
        try {
            CompetingAircraftDTO updated = competingAircraftService.update(id, dto);
            return ResponseEntity.ok(updated);
        } catch (Exception e) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
        }
    }

    /**
     * 删除竞争机型
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Integer id) {
        try {
            competingAircraftService.delete(id);
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
        }
    }
} 